<template>
  <div class="product-manager">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="statistics">
      <el-col :span="6" v-for="stat in statistics" :key="stat.title">
        <el-card shadow="hover">
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-title">{{ stat.title }}</div>
          <div
            class="stat-trend"
            :class="{ up: stat.trend > 0, down: stat.trend < 0 }"
          >
            较上月{{ stat.trend > 0 ? "+" : "" }}{{ stat.trend }}%
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增商品
        </el-button>
        <el-button type="success" @click="showCategoryDialog = true">
          <el-icon><FolderAdd /></el-icon>分类管理
        </el-button>
      </div>
      <div class="right">
        <!-- 商品分类多级选择 -->
        <el-cascader
          v-model="searchForm.classId"
          :options="categoryTree"
          :props="{
            value: 'class_id',
            label: 'class_name',
            children: 'children',
            emitPath: false,
            checkStrictly: true,
          }"
          placeholder="商品分类"
          clearable
          style="min-width: 180px"
        />
        <el-select v-model="searchForm.status" placeholder="商品状态" clearable>
          <el-option label="已上架" :value="1" />
          <el-option label="已下架" :value="0" />
        </el-select>
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索商品名称/ID"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-table :data="productList" stripe border v-loading="loading">
      <el-table-column prop="id" label="商品ID" width="80" />
      <el-table-column prop="image" label="商品图片" width="100">
        <template #default="{ row }">
          <el-image
            :src="
              Array.isArray(row.image) && row.image.length > 0 && row.image[0]
                ? row.image[0]
                : ''
            "
            :preview-src-list="
              Array.isArray(row.image) ? row.image.filter((url) => !!url) : []
            "
            fit="cover"
            :error="() => '图片加载失败'"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="原价" width="100">
        <template #default="{ row }"> ¥{{ row.price }} </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? "上架" : "下架" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            :type="row.status === 1 ? 'warning' : 'success'"
            size="small"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? "下架" : "上架" }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品编辑抽屉 -->
    <el-drawer
      v-model="showDrawer"
      :title="isEdit ? '编辑商品' : '新增商品'"
      size="85%"
      :destroy-on-close="true"
    >
      <div class="product-form">
        <el-form
          :model="productForm"
          :rules="rules"
          ref="productFormRef"
          label-width="100px"
        >
          <!-- 上半部分：基本信息 -->
          <div class="form-content">
            <div class="left-section">
              <el-form-item label="商品名称" prop="goodsName">
                <el-input v-model="productForm.goodsName" />
              </el-form-item>

              <el-form-item label="商品分类" prop="classId">
                <el-cascader
                  v-model="productForm.classId"
                  :options="categoryTree"
                  :props="{
                    value: 'class_id',
                    label: 'class_name',
                    children: 'children',
                    emitPath: false,
                    checkStrictly: true,
                  }"
                  placeholder="请选择商品分类"
                  clearable
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="商品图片" prop="goodsImages">
                <el-upload
                  v-model:file-list="productForm.imageList"
                  :http-request="handleUploadSuccess"
                  list-type="picture-card"
                  :limit="5"
                  :on-remove="handleImageRemove"
                  :auto-upload="true"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </el-form-item>

              <el-form-item label="商品简介" prop="goodsBrief">
                <el-input
                  type="textarea"
                  v-model="productForm.goodsBrief"
                  rows="3"
                  show-word-limit
                  maxlength="255"
                />
              </el-form-item>
            </div>

            <div class="right-section">
              <el-form-item label="秒杀价格" prop="seckillPrice">
                <el-input-number
                  v-model="productForm.seckillPrice"
                  :precision="2"
                  :step="10"
                  :min="0"
                  style="width: 180px"
                />
                <span class="unit">元</span>
              </el-form-item>

              <el-form-item label="原价" prop="originalPrice">
                <el-input-number
                  v-model="productForm.originalPrice"
                  :precision="2"
                  :step="10"
                  :min="0"
                  style="width: 180px"
                />
                <span class="unit">元</span>
              </el-form-item>

              <el-form-item label="库存数量" prop="stock">
                <el-input-number
                  v-model="productForm.stock"
                  :min="0"
                  :step="1"
                  style="width: 180px"
                />
                <span class="unit">件</span>
              </el-form-item>

              <el-form-item label="秒杀时间" prop="seckillTime">
                <el-date-picker
                  v-model="productForm.seckillTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  style="width: 380px"
                />
              </el-form-item>

              <el-form-item label="商品状态">
                <el-switch
                  v-model="productForm.goodsStatus"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="上架"
                  inactive-text="下架"
                />
              </el-form-item>

              <el-form-item label="规格参数">
                <div class="params-editor">
                  <div
                    v-for="(param, index) in productForm.goodsParams"
                    :key="index"
                    class="param-item"
                  >
                    <el-input
                      v-model="param.name"
                      placeholder="参数名"
                      style="width: 150px"
                    />
                    <el-input
                      v-model="param.value"
                      placeholder="参数值"
                      style="width: 200px"
                    />
                    <el-button
                      type="danger"
                      :icon="Delete"
                      circle
                      @click="removeParam(index)"
                    />
                  </div>
                  <el-button
                    type="primary"
                    plain
                    :icon="Plus"
                    @click="addParam"
                  >
                    添加规格
                  </el-button>
                </div>
              </el-form-item>
            </div>
          </div>

          <!-- 下半部分：商品详情 -->
          <div class="detail-section">
            <el-form-item label="商品详情" prop="description">
              <div class="editor-container">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  mode="default"
                />
                <Editor
                  style="height: 600px"
                  v-model="productForm.description"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleEditorCreated"
                />
              </div>
            </el-form-item>
          </div>
        </el-form>

        <div class="drawer-footer">
          <el-button @click="showDrawer = false">取消</el-button>
          <el-button type="primary" @click="handleSaveProduct">确定</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 分类管理抽屉 -->
    <el-drawer
      v-model="showCategoryDialog"
      title="商品分类管理"
      size="800px"
      direction="rtl"
      :destroy-on-close="true"
      class="category-drawer"
    >
      <div class="category-manager-drawer">
        <!-- 分类树和表格 -->
        <div class="category-tree-list">
          <el-tree
            :data="categoryTree"
            :props="treeProps"
            node-key="class_id"
            highlight-current
            default-expand-all
            @node-click="handleTreeNodeClick"
            class="category-tree"
          >
            <template #default="{ data }">
              <span>
                {{ data.class_name }}
                <el-tag
                  v-if="data.parent_id === 0"
                  size="small"
                  type="info"
                  style="margin-left: 6px"
                  >一级</el-tag
                >
                <el-tag
                  v-else-if="
                    categoryTree.some(
                      (item) => item.class_id === data.parent_id
                    )
                  "
                  size="small"
                  type="success"
                  style="margin-left: 6px"
                  >二级</el-tag
                >
                <el-tag
                  v-else
                  size="small"
                  type="warning"
                  style="margin-left: 6px"
                  >三级</el-tag
                >
              </span>
            </template>
          </el-tree>
        </div>
        <div class="category-form-upgrade">
          <el-form
            :model="categoryForm"
            :rules="categoryRules"
            ref="categoryFormRef"
            label-width="80px"
          >
            <el-form-item label="分类名称" prop="class_name">
              <el-input
                v-model="categoryForm.class_name"
                placeholder="请输入分类名称"
                clearable
                maxlength="20"
                show-word-limit
                class="category-input"
              />
            </el-form-item>
            <el-form-item label="父级分类" prop="parent_id">
              <el-cascader
                v-model="categoryForm.parent_id"
                :options="categoryTree"
                :props="{
                  value: 'class_id',
                  label: 'class_name',
                  children: 'children',
                  emitPath: false,
                  checkStrictly: true,
                  // 限定只能选择到二级
                  disabled: (node, data) => {
                    // 禁用三级及以上
                    const level = getCategoryLevel(node, 1);
                    return level > 2;
                  },
                }"
                placeholder="请选择父级分类"
                clearable
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="排序" prop="sort_order">
              <el-input-number
                v-model="categoryForm.sort_order"
                :min="0"
                :max="9999"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveCategory">
                {{ categoryForm.class_id ? "更新" : "添加" }}
              </el-button>
              <el-button v-if="categoryForm.class_id" @click="resetCategoryForm"
                >取消</el-button
              >
              <el-button
                v-if="categoryForm.class_id"
                type="danger"
                @click="deleteCategory(categoryForm)"
                style="margin-left: 10px"
                >删除</el-button
              >
            </el-form-item>
          </el-form>
          <div class="category-tip">
            <el-icon style="color: #e6a23c; margin-right: 4px"
              ><InfoFilled
            /></el-icon>
            支持多级分类，建议不超过3级且名称不超过20字。
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Delete,
  Edit,
  FolderAdd,
  InfoFilled,
  Search,
} from "@element-plus/icons-vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import {
  uploadProductImage,
  getProductCategoryList,
  addProductCategory,
  updateProductCategory,
  deleteProductCategory,
  addProduct,
  updateProduct,
  deleteProduct,
  getProductPagerList,
} from "@/api/api"; // 上传图片的API

// 统计数据
const statistics = ref([
  { title: "商品总数", value: 156, trend: 12.3 },
  { title: "上架商品", value: 86, trend: 5.6 },
  { title: "库存告警", value: 23, trend: -2.8 },
  { title: "本月新增", value: 45, trend: 8.9 },
]);

// 列表数据
const loading = ref(false);
const productList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref("");

// 搜索表单
const searchForm = reactive({
  classId: "",
  status: "",
  keyword: "",
});

// 商品分类数据
const categories = ref([
  { classId: 1, className: "手机数码" },
  { classId: 2, className: "电脑办公" },
  { classId: 3, className: "家用电器" },
]);

// 商品表单数据
const showDrawer = ref(false);
const isEdit = ref(false);
const productFormRef = ref(null);
const productForm = reactive({
  goodsId: null,
  goodsName: "",
  classId: "",
  goodsImages: "",
  imageList: [],
  goodsBrief: "",
  seckillPrice: 0,
  originalPrice: 0,
  stock: 0,
  goodsStatus: 1,
  seckillTime: [],
  description: "",
  goodsParams: [],
});

// 商品表单校验规则
const rules = {
  goodsName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  classId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
  goodsImages: [{ 
    required: true, 
    validator: (rule, value, callback) => {
      if (!productForm.imageList || productForm.imageList.length === 0) {
        callback(new Error("请上传至少一张商品图片"));
      } else {
        callback();
      }
    },
    trigger: "change"
  }],
  originalPrice: [
    { required: true, message: "请输入商品原价", trigger: "blur" },
  ],
  goodsBrief: [{ required: true, message: "请输入商品简介", trigger: "blur" }],
};

// 分类表单数据
const showCategoryDialog = ref(false);
const categoryFormRef = ref(null);
const categoryForm = reactive({
  class_id: null,
  class_name: "",
  parent_id: 0,
  sort_order: 0,
});
// 只允许选择一级分类作为父级分类
const parentCategoryOptions = ref([]);
const treeProps = { label: "class_name", children: "children" };

// 分类验证规则
const categoryRules = {
  className: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  parentId: [{ required: true, message: "请选择父级分类", trigger: "change" }],
};

// 编辑器相关
const editorRef = ref(null);
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入商品详细描述...",
};

// 修复：初始化编辑器
const handleEditorCreated = (editor) => {
  editorRef.value = editor;
};

// 获取商品列表（分页、搜索、筛选）
const getProductList = async () => {
  loading.value = true;
  try {
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      class_id: searchForm.classId || undefined,
      goods_status: searchForm.status !== "" ? searchForm.status : undefined,
      keyword: searchForm.keyword || undefined,
    };
    const res = await getProductPagerList(params);
    // console.log(res);

    // 适配后端返回结构
    if (res.code === 200) {
      const list = res.data?.data || [];
      productList.value = list.map((item) => {
        let imgs = [];
        try {
          imgs = JSON.parse(item.goods_images || "[]");

          // console.log("商品图片解析结果:", imgs[0]);
          // 过滤掉 blob 地址和空字符串，只保留 http/https 且非空
          imgs = imgs.filter(
            (url) => typeof url === "string" && /^https?:\/\//.test(url) && url
          );
        } catch {}
        return {
          ...item,
          image: imgs,
          name: item.goods_name,
          price: item.original_price,
          stock: item.stock,
          status: item.goods_status,
          id: item.goods_id,
          goods_id: item.goods_id,
        };
      });
      total.value = res.data?.total || 0;
    } else {
      ElMessage.error(res.message || "获取商品列表失败");
    }
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getProductList();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  getProductList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getProductList();
};

// 上传成功回调
const handleUploadSuccess = async (options) => {
  try {
    loading.value = true;
    const formData = new FormData();
    formData.append("image", options.file);
    const res = await uploadProductImage(formData);
    if (res.code === 200) {
      // 修正：只添加非空url
      if (!productForm.imageList) productForm.imageList = [];

      console.log("上传返回数据:", res.data);
      productForm.imageList.push({ url: res.data });

      console.log("上传成功:", productForm.imageList);
      // 只通过 onSuccess 回调，不再手动调用 ElMessage.success
      // options.onSuccess({
      //   name: options.file.name,
      //   url: res.data, // 确保这是完整的URL
      //   response: {
      //     // 如果需要，也可以添加response字段
      //     url: res.data,
      //   },
      // });
      ElMessage.success("商品图片上传成功");
    } else {
      options.onError(new Error(res.message || "上传失败"));
      ElMessage.error(res.message || "上传失败");
    }
  } catch (error) {
    console.error("上传错误:", error);
    options.onError(error);
    ElMessage.error("上传失败");
  } finally {
    loading.value = false;
  }
};

// 编辑商品
const handleEdit = (row) => {
  isEdit.value = true;
  // 回填表单
  Object.assign(productForm, {
    goodsId: row.goods_id,
    goodsName: row.goods_name,
    classId: row.class_id,
    goodsImages: row.goods_images,
    imageList: (() => {
      try {
        // 修复：转换为 { url } 数组
        const imgs = JSON.parse(row.goods_images || "[]");
        return imgs
          .filter(
            (url) => typeof url === "string" && /^https?:\/\//.test(url) && url
          )
          .map((url) => ({ url }));
      } catch {
        return [];
      }
    })(),
    goodsBrief: row.goods_brief,
    seckillPrice: row.seckill_price,
    originalPrice: row.original_price,
    stock: row.stock,
    goodsStatus: row.goods_status,
    seckillTime:
      row.start_time && row.end_time ? [row.start_time, row.end_time] : [],
    description: row.description,
    goodsParams: (() => {
      try {
        return JSON.parse(row.goods_params || "[]");
      } catch {
        return [];
      }
    })(),
  });
  showDrawer.value = true;
};

// 新增商品
const handleAdd = () => {
  isEdit.value = false;
  Object.assign(productForm, {
    goodsId: null,
    goodsName: "",
    classId: "",
    goodsImages: "",
    imageList: [],
    goodsBrief: "",
    seckillPrice: 0,
    originalPrice: 0,
    stock: 0,
    goodsStatus: 1,
    seckillTime: [],
    description: "",
    goodsParams: [],
  });
  showDrawer.value = true;
};

// 新增/编辑商品时，图片字段只存储图片地址数组（不含blob）
const handleSaveProduct = async () => {
  if (!productFormRef.value) return;

  try {
    await productFormRef.value.validate();
    // 处理图片数组
    const imageArr = (productForm.imageList || []).map(item => {
      // 优先使用 response.url，然后是 url，最后是字符串本身
      return item?.response?.url || item?.url || item;
    }).filter(url => typeof url === 'string' && /^https?:\/\//.test(url));

    if (imageArr.length === 0) {
      ElMessage.error("请上传至少一张商品图片1");
      return;
    }
    if (isEdit.value) {
      // 编辑商品
      const params = {
        goods_id: productForm.goodsId,
        goods_name: productForm.goodsName,
        goods_images: JSON.stringify(imageArr),
        class_id: productForm.classId,
        goods_params: JSON.stringify(productForm.goodsParams),
        seckill_price: productForm.seckillPrice,
        original_price: productForm.originalPrice,
        description: productForm.description,
        start_time: productForm.seckillTime?.[0] || null,
        end_time: productForm.seckillTime?.[1] || null,
        stock: productForm.stock,
        goods_brief: productForm.goodsBrief,
        goods_status: productForm.goodsStatus,
      };
      const res = await updateProduct(params);
      if (res.code === 200) {
        ElMessage.success("修改成功");
        showDrawer.value = false;
        getProductList();
      } else {
        ElMessage.error(res.message || "修改失败");
      }
    } else {
      // 新增商品
      const params = {
        goods_name: productForm.goodsName,
        goods_images: JSON.stringify(imageArr),
        class_id: productForm.classId,
        goods_params: JSON.stringify(productForm.goodsParams),
        seckill_price: productForm.seckillPrice,
        original_price: productForm.originalPrice,
        description: productForm.description,
        start_time: productForm.seckillTime?.[0] || null,
        end_time: productForm.seckillTime?.[1] || null,
        stock: productForm.stock,
        goods_brief: productForm.goodsBrief,
        goods_status: productForm.goodsStatus,
      };
      const res = await addProduct(params);
      if (res.code === 200) {
        ElMessage.success("添加成功");
        showDrawer.value = false;
        getProductList();
      } else {
        ElMessage.error(res.message || "添加失败");
      }
    }
  } catch (error) {
    console.log("表单验证失败", error);
  }
};

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该商品吗？", "警告", {
      type: "warning",
    });
    const res = await deleteProduct({ goods_id: row.goods_id || row.id });
    if (res.code === 200) {
      ElMessage.success("删除成功");
      getProductList();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error) {
    // 取消删除
  }
};

// 切换商品状态（上下架）
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? "下架" : "上架"}该商品吗？`,
      "提示"
    );
    const res = await updateProduct({
      goods_id: row.goods_id || row.id,
      goods_status: row.status === 1 ? 0 : 1,
    });
    if (res.code === 200) {
      ElMessage.success("操作成功");
      getProductList();
    } else {
      ElMessage.error(res.message || "操作失败");
    }
  } catch (error) {
    // 取消操作
  }
};

// 重置表单
const resetCategoryForm = () => {
  Object.assign(categoryForm, {
    class_id: null,
    class_name: "",
    parent_id: 0,
    sort_order: 0,
  });
  // 清除表单校验状态
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields();
  }
};

// 保存分类（区分添加和更新）
const saveCategory = async () => {
  if (!categoryForm.class_name) {
    ElMessage.warning("请输入分类名称");
    return;
  }
  let res;
  if (categoryForm.class_id) {
    // 更新
    res = await updateProductCategory(categoryForm);
  } else {
    // 添加
    res = await addProductCategory(categoryForm);
  }
  if (res.code !== 200) {
    ElMessage.error(res.message || "保存分类失败");
    return;
  } else {
    ElMessage.success(
      res.message || (categoryForm.class_id ? "分类更新成功" : "分类添加成功")
    );
    resetCategoryForm();
    loadCategoryTree();
  }
};

// 删除分类（支持表单内删除按钮）
const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm("确定要删除该分类吗？", "警告", {
      type: "warning",
    });
    const res = await deleteProductCategory({ class_id: category.class_id });
    if (res.code === 200) {
      ElMessage.success("删除成功");
      // 立即移除本地树和父级选项，提升响应速度
      removeCategoryFromTree(category.class_id);
      resetCategoryForm();
      // 重新拉取，确保和后端一致
      await loadCategoryTree();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch {
    // 取消删除
  }
};

// 辅助函数：递归移除本地树节点
function removeCategoryFromTree(classId) {
  function removeNode(list, id) {
    for (let i = list.length - 1; i >= 0; i--) {
      if (list[i].class_id === id) {
        list.splice(i, 1);
      } else if (list[i].children && list[i].children.length) {
        removeNode(list[i].children, id);
      }
    }
  }
  removeNode(categoryTree.value, classId);
  // 同步父级选项
  parentCategoryOptions.value = parentCategoryOptions.value.filter(
    (item) => item.class_id !== classId
  );
}

// 分类树结构
const categoryTree = ref([]);

// 加载分类树（支持三级及多级）
const loadCategoryTree = async () => {
  categoryTree.value = [];
  const res = await getProductCategoryList();
  if (res.code !== 200) {
    ElMessage.error(res.message || "加载分类失败");
    return;
  }
  const flatList = res.data || [];
  // 支持多级分类的树构建
  const buildTree = (list, parent_id = 0) => {
    return list
      .filter((item) => item.parent_id === parent_id)
      .sort((a, b) => a.sort_order - b.sort_order)
      .map((item) => ({
        ...item,
        children: buildTree(list, item.class_id),
      }));
  };
  categoryTree.value = buildTree(flatList);
  // 只用于商品表单的分类下拉
  parentCategoryOptions.value = flatList.filter((item) => item.parent_id === 0);
};

// 分类表单父级分类选择支持三级
// 只允许选择非自身及其子孙节点为父级
const isDescendant = (list, id, targetId) => {
  // 判断targetId是否为id的子孙
  const node = list.find((item) => item.class_id === id);
  if (!node || !node.children) return false;
  for (const child of node.children) {
    if (
      child.class_id === targetId ||
      isDescendant(child.children || [], child.class_id, targetId)
    ) {
      return true;
    }
  }
  return false;
};

// 点击树节点编辑
const handleTreeNodeClick = (data) => {
  Object.assign(categoryForm, {
    class_id: data.class_id,
    class_name: data.class_name,
    parent_id: data.parent_id ?? 0,
    sort_order: data.sort_order ?? 0,
  });
  if (categoryFormRef.value) categoryFormRef.value.clearValidate();
};

// 分类表单父级分类下拉过滤（不能选自己和子孙）
const filteredParentCategoryOptions = computed(() => {
  if (!categoryForm.class_id) return parentCategoryOptions.value;
  // 过滤掉自己和子孙节点
  const excludeIds = new Set();
  const collectDescendants = (id) => {
    excludeIds.add(id);
    const node = categoryTree.value
      .flat(Infinity)
      .find((item) => item.class_id === id);
    if (node && node.children) {
      node.children.forEach((child) => collectDescendants(child.class_id));
    }
  };
  collectDescendants(categoryForm.class_id);
  return parentCategoryOptions.value.filter(
    (item) => !excludeIds.has(item.class_id)
  );
});

// 获取分类层级（递归向上查找）
function getCategoryLevel(node, level = 1) {
  if (!node.parent) return level;
  return getCategoryLevel(node.parent, level + 1);
}

// 初始化
loadCategoryTree();
getProductList();
</script>

<style lang="scss" scoped>
.product-manager {
  padding: 20px;

  .statistics {
    margin-bottom: 20px;

    .el-card {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      border-radius: 8px;
      transition: all 0.3s;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .stat-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }

      .stat-trend {
        font-size: 12px;
        &.up {
          color: #67c23a;
        }
        &.down {
          color: #f56c6c;
        }
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }

  .action-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .left {
      display: flex;
      gap: 10px;
    }

    .right {
      display: flex;
      gap: 10px;

      .el-select,
      .el-input {
        min-width: 180px;
      }
    }
  }

  .el-table {
    .el-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .product-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 148px;
    height: 148px;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      border-color: #409eff;
    }

    .preview-image {
      width: 146px;
      height: 146px;
      object-fit: cover;
    }

    .uploader-icon {
      font-size: 28px;
      color: #8c939d;
    }
  }

  .product-form {
    padding: 20px;
    height: calc(100vh - 120px);
    overflow-y: auto;

    .form-content {
      display: flex;
      gap: 40px;
      margin-bottom: 30px;
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

      .left-section {
        width: 45%;
      }

      .right-section {
        width: 55%;
      }
    }

    .detail-section {
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      width: 100%;

      .editor-container {
        border: 1px solid #ddd;
        border-radius: 4px;

        .toolbar {
          background: #f5f7fa;
          border-bottom: 1px solid #ddd;
        }
      }
    }

    .drawer-footer {
      position: sticky;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 20px;
      background: #fff;
      text-align: right;
      border-top: 1px solid #f0f0f0;
      margin: 0 -20px;

      .el-button {
        margin-left: 8px;
      }
    }
  }

  .category-manager {
    display: flex;
    gap: 20px;

    .category-list {
      flex: 1;
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .el-table {
        .el-table-column {
          text-align: center;
        }
      }
    }

    .category-form {
      flex: 1;
      background: #f9f9f9;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .el-form-item {
        margin-bottom: 15px;
      }
    }
  }

  .category-drawer {
    .el-drawer__body {
      padding: 0 32px 32px 32px;
      background: #f8f9fb;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
    }
  }

  .category-manager-drawer {
    display: flex;
    flex-direction: row;
    gap: 36px;
    min-height: 400px;

    .category-tree-list {
      flex: 1.1;
      background: #fff;
      border-radius: 10px;
      padding: 24px 12px 12px 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      margin-bottom: 18px;
      min-width: 260px;
      .category-tree {
        min-width: 200px;
      }
    }

    .category-form-upgrade {
      flex: 1.7;
      background: linear-gradient(135deg, #f5f7fa 0%, #e9f0fb 100%);
      border-radius: 10px;
      padding: 36px 28px 24px 28px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);

      .category-input {
        width: 100%;
      }

      .el-form-item {
        margin-bottom: 18px;
      }

      .category-tip {
        margin-top: 24px;
        font-size: 14px;
        color: #999;
        display: flex;
        align-items: center;
        background: #fffbe6;
        border-radius: 4px;
        padding: 10px 16px;
      }
    }
  }
}
</style>
